package com.example.petplatform.service;

import com.example.petplatform.dao.LoginDao;
import com.example.petplatform.entity.Admin;
import com.example.petplatform.entity.Param.Params;
import com.example.petplatform.entity.Users;
import com.example.petplatform.exception.CustomException;
import com.example.petplatform.Utils.JwtTokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    @Resource
    private LoginDao loginDao;

    /**
     * 管理员登录
     */
    public Admin adminLogin(Params params) {
        Admin admin = loginDao.adminLogin(params.getUsername(), params.getPassword());
        if (admin == null) {
            throw new CustomException("用户名或密码错误");
        }
        String token = JwtTokenUtils.genToken(admin.getId().toString(), admin.getPassword());
        admin.setToken(token);
        return admin;
    }

    /**
     * 用户登录
     */
    public Users userLogin(Params params) {
        Users user = loginDao.userLogin(params.getUsername(), params.getPassword());
        if (user == null) {
            throw new CustomException("用户名或密码错误");
        }
        String token = JwtTokenUtils.genToken(user.getId().toString(), user.getPassword());
        user.setToken(token);
        return user;
    }

    /**
     * 用户注册
     */
    public Users userRegister(Users users) {
        // 通过用户名进行重复性判断
        Users existingUser = loginDao.getUserByUsername(users.getUsername());
        if (existingUser != null) {
            throw new CustomException("用户名已存在，请重新输入！");
        }
        // 插入新的记录
        loginDao.insertUserSelective(users);
        // 返回新注册的用户信息
        return users;
    }


    public Users getAdminById(Integer id) {
        return  loginDao.selectByPrimaryKey(id);
    }


}
